package com.taobao.ad.hadoop.utility;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class DateUtil {
	private static Date date = new Date(); 
	private static Map<String, SimpleDateFormat> sdfMap = new HashMap<String, SimpleDateFormat>();
	private static SimpleDateFormat getSimpleDateFormat(String fmt){
		if(sdfMap.containsKey(fmt)){
			return sdfMap.get(fmt);
		}else{
			SimpleDateFormat sdf = new SimpleDateFormat(fmt);
			sdfMap.put(fmt, sdf);
			return sdf;
		}
	}
	
	public static Date getDate(){
		return getDate(getSeconds());
	}
	public static Date getDate(int seconds) { 
		date.setTime(seconds * 1000L); 
		return date;
	}
	public static Date getDate(long milliseconds) { 
		date.setTime(milliseconds); 
		return date;
	}
	public static Date getDate(String datetimeStr, String fmt) {
		if (StringUtil.IsEmpty(datetimeStr) || StringUtil.IsEmpty(fmt)){
			return null;
		}
		SimpleDateFormat sdf = DateUtil.getSimpleDateFormat(fmt);
		Date date = null; 
		try {
			date = sdf.parse(datetimeStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}
	
	public static int getSeconds() {
		return (int) (Calendar.getInstance().getTimeInMillis() / 1000L);
	}
	public static int getSeconds(Date date) {
		if (date == null)
			return 0;
		return (int) (date.getTime() / 1000L);
	}
	public static int getSeconds(String datetimeStr, String fmt) {
		return getSeconds(getDate(datetimeStr, fmt));
	}
	
	public static int GetSecondsSpan(Date date1, Date date2) {
		return getSeconds(date2) - getSeconds(date1);
	}
	public static int GetDaySpan(Date date1, Date date2) {
		return getSeconds(date2) / 86400 - getSeconds(date1) / 86400;
	}
	
	public static String getDateTiString(){
		return getDateTimeString(getDate());
	}
	public static String getDateTimeString(Date date) {
		return DateFormat.getDateTimeInstance().format(date);
	}
	public static String GetDateTimeString(Date date, String fmt) {
		SimpleDateFormat sdf = getSimpleDateFormat(fmt);
		return sdf.format(date);
	}
	public static String GetDateTimeString(int seconds, String fmt) {
		Date date = getDate(seconds);
		return GetDateTimeString(date, fmt);
	}
}
